﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class Share : System.Web.UI.Page
{
    List<_User> User_list = new List<_User>();

    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.IsAuthenticated == false)
        {
            Response.Redirect("login.aspx");
        }

        if (Request.IsAuthenticated)
        {
            string n = "";
            SqlCommand sCmd = new SqlCommand("SELECT name FROM USERS WHERE id=@id", conn);
            sCmd.Parameters.Add(new SqlParameter("@id", SqlDbType.Int)).Value = User.Identity.Name;
            conn.Open();
            SqlDataReader dr = sCmd.ExecuteReader();
            while (dr.Read())
            {
                string name = Convert.ToString(dr[0].ToString());
                n = name;
            }
            dr.Close();
            conn.Close();

            WelcomeBackMessage.Text = "Welcome back, " + n + "!";

            AuthenticatedHeaderPanel.Visible = true;
            AuthenticatedMessagePanel.Visible = true;
            AuthenticatedMenuPanel.Visible = true;

            if (!IsPostBack)
            {
                SetData();
            }
        }
        else
        {
            AuthenticatedHeaderPanel.Visible = false;
            AuthenticatedMessagePanel.Visible = false;
            AuthenticatedMenuPanel.Visible = false;
        }
    }
    private string Sort
    {
        get
        {
            return String.Concat(SortExpression, (SortDirection == SortDirection.Ascending) ? " DESC" : " ASC");
        }
    }
    private SortDirection SortDirection
    {
        get
        {
            if (ViewState["SortDirection"] == null)
            {
                ViewState["SortDirection"] = SortDirection.Descending;
            }

            return (SortDirection)ViewState["SortDirection"];
        }
        set { ViewState["SortDirection"] = value; }
    }
    private string SortExpression
    {
        get
        {
            if (ViewState["SortExpression"] == null)
            {
                ViewState["SortExpression"] = "ID";
            }

            return ViewState["SortExpression"].ToString();
        }
        set { ViewState["SortExpression"] = value; }
    }

    protected void ListView1_Sorting(object sender, ListViewSortEventArgs e)
    {
        if (SortExpression.Equals(e.SortExpression))
        {
            SortDirection = (SortDirection == SortDirection.Descending)
                  ? SortDirection.Ascending
                  : SortDirection.Descending;
        }
        else
        {
            SortDirection = SortDirection.Descending;
        }

        SortExpression = e.SortExpression;
        SetData();
    }

    private void SetData()
    {
        User_list = _User.SelUser(User.Identity.Name);

        if (User_list.Count == 0)
        {
            message.Visible = true;
            bt_share.Visible = false;
        }
        else
        {
            message.Visible = false;
            ListView1.DataSource = User_list;
            ListView1.DataBind();
            bt_share.Visible = true;

            string docNum;
            Response.Write(docNum = Session["Doc_Num"].ToString());

            string userID;
            Response.Write(userID = Session["userID"].ToString());

            List<int> users = new List<int>();
            SqlCommand SelCmd = new SqlCommand("SELECT id_issued_by_user FROM document WHERE document_number=@doc_num", conn);
            SelCmd.Parameters.Add(new SqlParameter("doc_num", SqlDbType.NVarChar)).Value = docNum;
            conn.Open();
            SqlDataReader dr = SelCmd.ExecuteReader();
            while (dr.Read())
            {
                users.Add(Convert.ToInt32(dr["id_issued_by_user"].ToString()));
                if (users.Contains(Convert.ToInt32(userID)))
                {
                    users.Remove(Convert.ToInt32(userID));
                }
            }
            dr.Close();
            conn.Close();

            foreach (ListViewItem item in ListView1.Items)
            {
                CheckBox cb = (CheckBox) item.FindControl("check_share");
                foreach (int user in users)
                {
                    Label id_user = (Label) item.FindControl("idLabel");
                    string user_id = id_user.Text;
                    if(user_id == user.ToString())
                    {
                        cb.Checked = true;
                    }
                }
            }
            Response.Clear();
        }
    }

    protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        e.Item.FindControl("idL").Visible = false;
    }

    protected void bt_share_Click(object sender, EventArgs e)
    {
        string docID;
        Response.Write(docID = Session["Doc_ID"].ToString());

        string doc_num = " ";
        string doc_date = " ";
        string doc_pay_date = " ";
        string comp_by = " ";
        string comp_to = " ";
        string doc_type = " ";
        string pay_type = " ";
        string del_place = " ";
        string address_comp_by = " ";
        string address_client_to = " ";
        string bank_company_by = " ";
        string bank_client_to = " ";
        string account_company_by = " ";
        string account_client_to = " ";
        string statuss = " ";

        conn.Open();
        SqlCommand selCmd =new SqlCommand("SELECT * FROM document WHERE id=@document_id",conn);
        selCmd.Parameters.Add(new SqlParameter("@document_id", SqlDbType.Int)).Value = docID;
        SqlDataReader dr = selCmd.ExecuteReader();
        while (dr.Read())
        {
            doc_num = dr[1].ToString();
            doc_date = dr[2].ToString();
            doc_pay_date = dr[3].ToString();
            comp_by = dr[5].ToString();
            comp_to = dr[6].ToString();
            doc_type = dr[8].ToString();
            pay_type = dr[9].ToString();
            del_place = dr[10].ToString();
            address_comp_by = dr[11].ToString();
            address_client_to = dr[12].ToString();
            bank_company_by = dr[13].ToString();
            bank_client_to = dr[14].ToString();
            account_company_by = dr[15].ToString();
            account_client_to = dr[16].ToString();
            statuss = dr[17].ToString();
        }
        dr.Close();
        conn.Close();

        string docNum;
        Response.Write(docNum = Session["Doc_Num"].ToString());

        string userID;
        Response.Write(userID = Session["userID"].ToString());

        List<int> users = new List<int>();
        SqlCommand SelCmd = new SqlCommand("SELECT id_issued_by_user FROM document WHERE document_number=@doc_num", conn);
        SelCmd.Parameters.Add(new SqlParameter("doc_num", SqlDbType.NVarChar)).Value = docNum;
        conn.Open();
        SqlDataReader dr2 = SelCmd.ExecuteReader();
        while (dr2.Read())
        {
            users.Add(Convert.ToInt32(dr2["id_issued_by_user"].ToString()));
            if (users.Contains(Convert.ToInt32(userID)))
            {
                users.Remove(Convert.ToInt32(userID));
            }
        }
        dr2.Close();
        conn.Close();

        List<int> user = new List<int>();
        List<int> user2 = new List<int>();
        foreach (ListViewItem item in ListView1.Items)
        {
            CheckBox cb = (CheckBox) item.FindControl("check_share");
            if (cb.Checked)
            {
                Label id_user = (Label) item.FindControl("idLabel");
                int user_id = Convert.ToInt32(id_user.Text);
                user.Add(user_id);
                foreach (int us in users)
                {
                    if (user.Contains(us))
                    {
                        user.Remove(us);
                    }
                }
            }
            
            if (cb.Checked == false)
            {
                Label id_user = (Label)item.FindControl("idLabel");
                int user_id = Convert.ToInt32(id_user.Text);
                user2.Add(user_id);
            }
        }

        foreach (var i in user2)
        {
            SqlCommand DelCmd = new SqlCommand("DELETE FROM document WHERE document_number=@doc_num AND id_issued_by_user=@user_id", conn);
            DelCmd.Parameters.Add(new SqlParameter("doc_num", SqlDbType.NVarChar)).Value = docNum;
            DelCmd.Parameters.Add(new SqlParameter("user_id", SqlDbType.Int)).Value = i;
            conn.Open();
            DelCmd.ExecuteNonQuery();
            conn.Close();
        }

        foreach (int id in user)
        {
            _Invoice.Insert(doc_num, doc_date, doc_pay_date, id.ToString(), comp_by, comp_to, doc_type, pay_type,del_place,address_comp_by,address_client_to,bank_company_by,bank_client_to,account_company_by,account_client_to, statuss);
        }

        Session.Clear();
        Response.Redirect("default.aspx");
    }
}